package com.fxm.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fxm.dao.VisitMapper;
import com.fxm.domain.Visit;
import com.fxm.service.VisitService;
import com.fxm.utils.TimeUtilCustomize;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.Objects;

/**
 * <p>
 * 访问量表 服务实现类
 * </p>
 *
 * @author fxm
 * @since 2021-02-24
 */
@Slf4j
@Service
public class VisitServiceImpl extends ServiceImpl<VisitMapper, Visit> implements VisitService {

    @Async
    @Override
    public void visitDataAccess(Integer value) {

        //当前时间 格式：yyyy-MM-dd HH:00:00
        String dateH = TimeUtilCustomize.parseDateToStr(TimeUtilCustomize.DATE_TIME_FORMAT_H, new Date());
        //当前时间 格式：yyyy-MM-dd
        String dateD = TimeUtilCustomize.parseDateToStr(TimeUtilCustomize.DATE_DAY_FORMAT, new Date());

        //判断当前时间记录 数据库中是否存在
        Visit visit = checkExits(dateH);

        if (Objects.isNull(visit)) {
            //不存在 则添加
            insertVisit(value, dateH, dateD);
        }else {
            //存在 则更新
            updateVisit(value, dateH);
        }
    }

    /**
     * 更新访问量
     * @param value
     */
    private void updateVisit(Integer value, String dateH) {
        QueryWrapper<Visit> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(Visit::getDt, dateH)
                             .eq(Visit::getDeleted, 0);
        Visit visit = baseMapper.selectOne(queryWrapper);
        //更新访问量
        Integer oldVisit = visit.getVisit();
        int newVisit = oldVisit + value;
        visit.setVisit(newVisit);
        baseMapper.updateById(visit);
    }

    /**
     * 添加访问量数据
     * @param value
     */
    private void insertVisit(Integer value, String dateH, String dateD) {

        Visit visit = Visit.builder()
                .dt(dateH)
                .dtD(dateD)
                .visit(value)
                .build();

        baseMapper.insert(visit);
    }

    /**
     * 判断当前时间记录 数据库是否存在
     * @param date
     * @return
     */
    private Visit checkExits(String date) {
        QueryWrapper<Visit> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(Visit::getDt, date)
                .eq(Visit::getDeleted, 0);
        Visit visit = baseMapper.selectOne(queryWrapper);
        return visit;
    }
}
